package com.xie.controller;

import com.sun.org.apache.xpath.internal.operations.Mod;
import com.xie.pojo.Student;
import com.xie.pojo.Teacher;
import com.xie.service.StudentService;
import com.xie.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;

@Controller
public class MyController {

    @Autowired
    @Qualifier("TeacherServiceImpl")
    private TeacherService teacherService;

    @Autowired
    @Qualifier("StudentServiceImpl")
    private StudentService studentService;

    @RequestMapping("/welcome")
    public String welcome(){
        return "welcome";
    }
    @RequestMapping("/welcomes")
    public String studentWelcome(){
        return "welcomes";
    }

    @RequestMapping("/toLogin")
    public String toLogin(){
        return "login";
    }
    @RequestMapping("/login")
    public String login(@RequestParam("uid") String uid, @RequestParam("pwd") String pwd, @RequestParam("isno") String isno, HttpSession session){
        if (isno.equals("1")){
            Teacher teacher = new Teacher();
            teacher.setTid(uid);
            teacher.setPwd(pwd);
            Teacher teacher1 = teacherService.loginTeacher(teacher);
            session.setAttribute("teacher",teacher1);
            return "redirect:/welcome";
        }else {
            Student student = new Student();
            student.setSid(uid);
            student.setPwd(pwd);
            Student student1 = studentService.loginStudent(student);
            session.setAttribute("student",student1);
            return "redirect:/welcomes";
        }
    }

    @RequestMapping("/exit")
    public String exit(HttpSession session){
        session.removeAttribute("teacher");
        session.removeAttribute("student");
        return "redirect:/toLogin";
    }


    @RequestMapping("/toUpload")
    public String toUpload(){
        return "upload";
    }
    @RequestMapping("/upload")
    public String upload(HttpServletRequest req, @RequestParam("subFile") CommonsMultipartFile file, HttpSession session) throws IOException {
        String path = req.getSession().getServletContext().getRealPath("/upload");

        File realPath = new File(path);
        if(!realPath.exists()){
            realPath.mkdir();
        }


        file.transferTo(new File(realPath + "/" +file.getOriginalFilename()));
        session.setAttribute("msg","上传成功");
        return "redirect:/toUpload";
    }

}
